package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 检查用户登录状态
func CheckLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		var token string
		auth := c.GetHeader("Authorization")
		if strings.HasPrefix(auth, "Bearer ") {
			token = auth[7:]
		} else if token, _ = c.Cookie("token"); token == "" {
			token = c.Query("token")
		}

		if token == "" {
			c.Redirect(http.StatusSeeOther, "/login")
			c.Abort()
		} else {
			userinfo, err := ParseToken(token)
			if err != nil {
				logrus.Errorln("解析Token签名失败:", err)
				c.Abort()
				return
			}
			c.Set("user", userinfo)
		}
	}

}
